<?php

namespace App\Http\Controllers\Api\Client;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class WechatController extends Controller
{
    protected $orderService;

//    public function __construct(OrderService $orderService)
//    {
//        $this->orderService = $orderService;
//    }

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');
        $wechat->server->setMessageHandler(function ($message) {
            return "欢迎关注 overtrue！";
        });

        Log::info('return response.');

        return $wechat->server->serve();
    }

    /**
     * @return Users|\Illuminate\Database\Eloquent\Model|null|static
     */
    public function getOauth()
    {
//        $config = [
//            'app_id' => env('WECHAT_APPID', 'your-app-id'),             // AppID
//            'secret' => env('WECHAT_SECRET', 'your-app-secret'),        // AppSecret
//        ];
//        $app = new Application($config);
//        $oauth = $app->oauth;
//        // 获取 OAuth 授权结果用户信息
//        $user = $oauth->user();
//        $userArray = $user->toArray();
//
//        $userModel = Users::where('open_id', $userArray['open_id'])->first();
//        if (!$userModel) {
//            $userModel = new Users();
//            $userModel->open_id = $userArray['open_id'];
//            $userModel->name = $userArray['name'];
//            $userModel->avator = $userArray['avator'];
//            $userModel->api_token = $userArray['open_id'];
//            $userModel->save();
//        }
//        $userModel->api_token = $userModel->open_id;
//        return $userModel;
        \EasyWeChat::oauth()->scopes(['snsapi_userinfo'])
            ->redirect(config('app.url').'/api/wechat/callback');
    }

    /**
     * 微信认证
     * @return \Illuminate\Contracts\Routing\ResponseFactory|mixed|string|\Symfony\Component\HttpFoundation\Response
     */
    public function callback(Request $request)
    {
        $returnUrl = $request->get('returnUrl', null);
        \Log::info(['info' => $returnUrl]);
        $user = $request->session()->get('wechat.oauth_user');
        $openId = $user->id;
        $userModel = Users::where('open_id', $openId)->first();
        $isNewUserModel = 0;
        if (!$userModel) {
            $userModel = new Users();
            $isNewUserModel = 1;
        }
        $userModel->open_id = $openId;
        $userModel->name = $user->name;
        $userModel->avator = $user->avatar;

        if ($userModel->avator === '\0') {
            $userModel->avator = 'http://xbs-bucket.oss-cn-beijing.aliyuncs.com/avator/default.png';
        }
        $userModel->api_token = str_random(60);
        \Log::debug($userModel->toJson(JSON_UNESCAPED_UNICODE));
        if (!$userModel->save()) {
            return response('认证失败！', 403);
        }
        if ($isNewUserModel == 1) {
            $order = new Order();
            $order->id = 0;
            $order->users_id = $userModel->id;
            $order->product_total = 0;
            $order->shipping = 0;
            event(new RegisterEvent($order));
        }

        $home = config('app.wechat');
        if ($returnUrl) {
            return redirect()->to($home.'/#' . $returnUrl . '?api_token=' . $userModel->api_token);
        } else {
            return redirect()->to($home.'/#/?api_token=' . $userModel->api_token);
        }
    }

    /**
     * @param $openId
     * @return Users|\Illuminate\Database\Eloquent\Model|null|static
     */
    public function getUser($openId)
    {
        $user = Users::where('open_id', $openId)->first();
        if ($user) {
            return $user;
        }
        return new Users();
    }

    /**
     * 获取微信jssdk接口
     * @param Request $request
     * @return array|string
     */
    public function getWeChatJsSdk(Request $request)
    {
        $url = $request->get('url');
        $js = \EasyWeChat::jssdk;
        $js->setUrl($url);
        $config = $js->buildConfig(array('onMenuShareAppMessage', 'onMenuShareTimeline', 'chooseWXPay', 'hideAllNonBaseMenuItem', 'getLocation', 'openLocation'));

        \Log::debug(json_encode($config, JSON_UNESCAPED_UNICODE));
        return $config;
    }

    /**
     * 微信支付-结果通知
     * @param Request $request
     * @return array|string
     *
     * Todo: 增加 支付记录
     */
    public function payCallback(Request $request)
    {
        $response = \EasyWeChat::payment()->handleNotify(function ($notify, $successful) {
            \Log::debug('支付信息'.json_encode($notify, JSON_UNESCAPED_UNICODE));
            \Log::debug('支付结果'.json_encode($successful, JSON_UNESCAPED_UNICODE));
            try {
                // 支付成功
                if ($successful) {
                    $order = Order::where('sn', $notify->out_trade_no)->first();
                    $this->orderService->payOrder($order);
                }
                return true; // 处理完成
            } catch (\Exception $e) {
                \Log::debug($e->getTraceAsString());
                return false; // 处理完成
            }

        });
//        $response->send(); // Laravel 里请使用：return $response;
        return $response;
    }
}
